import axios from 'axios';
import proxy from '../configs/host';
import { createBrowserHistory } from 'history';
import { message } from 'tdesign-react';

const env = import.meta.env.MODE || 'development';
const API_HOST = proxy[env].API;
const SUCCESS_CODE = 200;
const TIMEOUT = 5000;
const history = createBrowserHistory();
export const instance = axios.create({
  baseURL: API_HOST,
  timeout: TIMEOUT,
});
instance.interceptors.request.use(
  (config: any) => {
    const token = localStorage.getItem('token');
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token || ''}`,
    };
    return config;
  },
  (e) => Promise.reject(e),
);
instance.interceptors.response.use(
  // eslint-disable-next-line consistent-return
  (response) => {
    if (response.status === 200) {
      const { data } = response;
      if ((data.code||data.status) === SUCCESS_CODE) {
        return data;
      }
      return Promise.reject(data);
    }
    return Promise.reject(response?.data);
  },
  (err) => {
    const token = localStorage.getItem('token');
    if (err.status == 403 || !token) {
      message.error('登录已过期，请重新登录~');
      setTimeout(() => {
        history.push('/login');
        location.reload();
      }, 1000);
      return
    }
    return Promise.reject(err);
  },
);

export default instance;
